//
//  TimingViewController.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/8/31.
//

import UIKit
import AudioToolbox

class TimingViewController: BaseViewController {

    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var secondsLabel: UILabel!
    @IBOutlet weak var endTimeLabel: UILabel!
    @IBOutlet weak var startBtn: UIButton!
    @IBOutlet weak var meteringBtn: UIButton!
    @IBOutlet weak var recordsTableView: UITableView!
    
    /// 计时器实体类
    var customTimer: CustomTimer!
    /// 开始时间
    private var startTime: TimeInterval = 0
    /// 结束时间
    private var endTime: TimeInterval = 0
    /// 最后一次时间戳
    private var lastTime: TimeInterval = 0
    
    var type: TimeStatisticsType = .xingce
    
    private var currentBrightness: CGFloat = 0
    
    /// 计次数
    private var times: Int = 0
    private var records = [TimeRecord]()
    
    /// 总秒数
    private var totalSeconds: Int = 0
    
    /// 时间差，  计时器是从1秒开始的，需要让它少记一秒
    private var timeDifference: Int = -1

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 强制暗黑模式
        navigationController?.overrideUserInterfaceStyle = .dark
        setupUI()
        showTime(time: startTime, seconds: totalSeconds)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        UIApplication.shared.isIdleTimerDisabled = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        UIApplication.shared.isIdleTimerDisabled = false
        // 取消强制暗黑模式
        navigationController?.overrideUserInterfaceStyle = .unspecified
    }
    
    deinit {
        UIScreen.main.brightness = currentBrightness
    }
    
    @IBAction func clickStartBtn(_ sender: Any) {
        AudioServicesPlaySystemSound(1103)
        
        clickStartBtn2()
    }
    
    private func clickStartBtn2() {
        if startBtn.isSelected {
            startBtn.setTitle("启动", for: .normal)
            pauseTimer()
        } else {
            startBtn.setTitle("暂停", for: .normal)
            setupTimer(count: 1)
            startTimer()
        }
        startBtn.isSelected.toggle()
        meteringBtn.isEnabled = startBtn.isSelected
    }
    
    @IBAction func clickMeteringBtn(_ sender: Any) {
        AudioServicesPlaySystemSound(1103)
        if type == .calculate { // 是速算，计次后暂停计时
            clickStartBtn2()
        }
        
        times = times + 1
        
        let title = "计次\(times)"
        var timeStr = ""
        if customTimer.type == TimerType.timeSlotTiming.id {
            timeStr = formatTime(timeInterval: startTime)
        }
        let intervalSeconds = abs(Int(startTime - lastTime))
        let record = TimeRecord(title: title, timeStr: timeStr, seconds: intervalSeconds, totalSeconds: totalSeconds)
        lastTime = startTime
        
        records.insert(record, at: 0)
        recordsTableView.reloadData()
        
        if let customTimer = customTimer {
            TimeStatisticsStore.record(uuid: uuid, duration: TimeInterval(totalSeconds), timer: customTimer)
        }
    }
    
    private func setupUI() {
        title = customTimer?.name
        endTimeLabel.textColor = .systemGray2
        
        switch customTimer.type {
        case TimerType.timeSlotTiming.id:
            startTime = customTimer?.startTime ?? 0
            endTime = customTimer?.endTime ?? 0
            endTimeLabel.isHidden = false
            endTimeLabel.text = formatTime(timeInterval: customTimer?.endTime ?? 0)
        case TimerType.timer.id:
            startTime = 0
            endTimeLabel.isHidden = true
            secondsLabel.isHidden = true
        case TimerType.countDown.id:
            startTime = customTimer.duration
            endTimeLabel.isHidden = true
            secondsLabel.isHidden = true
        default: break
        }
        
        lastTime = startTime
        
        meteringBtn.isEnabled = false
        currentBrightness = UIScreen.main.brightness
        
        startBtn.setFillet(cornerRadius: startBtn.frame.width / 2)
        meteringBtn.setFillet(cornerRadius: meteringBtn.frame.width / 2)
        startBtn.setBackgroundImage(UIImage.imageWithColor(.systemGreen), for: .normal)
        startBtn.setBackgroundImage(UIImage.imageWithColor(.systemOrange), for: .selected)
        meteringBtn.setBackgroundImage(UIImage.imageWithColor(.systemGreen), for: .normal)
        meteringBtn.setBackgroundImage(UIImage.imageWithColor(.systemGray3), for: .disabled)
        
        recordsTableView.delegate = self
        recordsTableView.dataSource = self
        recordsTableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "设置", style: .plain, target: self, action: #selector(jumpSettings))
        
        let flag = UserDefaults.standard.bool(forKey: kUserDefaults_BrightnessSwitch)
        if flag {
            let value = UserDefaults.standard.float(forKey: kUserDefaults_BrightnessValue)
            UIScreen.main.brightness = CGFloat(value)
        }
    }
    
    @objc private func jumpSettings() {
        let vc = TimingSettingsController()
        vc.currentBrightness = currentBrightness
        navigationController?.pushViewController(vc, animated: true)
    }
    
    override func timing() {
        super.timing()
        
        if timeDifference == -1 {
            timeDifference = timeDifference + 1
            return
        }
        
        // 倒计时
        if customTimer.type == TimerType.countDown.id {
            countdown()
            return
        }
        
        startTime = startTime + 1
        totalSeconds = totalSeconds + 1
        showTime(time: startTime, seconds: totalSeconds)
        
        if customTimer.type == TimerType.timeSlotTiming.id {
            // 计时结束
            if startTime >= endTime {
                pauseTimer()
                SpeechTool.speech("考试结束")
            }
            // TODO: 语音提示
    //        else if startTime == kTime09_45 {
    //            SpeechTool.speech("距离考试结束还有15分钟")
    //        }
        }
        
    }
    
    /// 倒计时
    private func countdown() {
        startTime = startTime - 1
        totalSeconds = totalSeconds + 1
        showTime(time: startTime, seconds: totalSeconds)
        
        // 计时结束
        if startTime == 0 {
            pauseTimer()
            SpeechTool.speech("计时结束")
        }
    }
    
    private func showTime(time: TimeInterval, seconds: Int) {
        if customTimer.type == TimerType.timeSlotTiming.id {
            let timeStr = formatTime(timeInterval: startTime)
            timeLabel.text = timeStr
            secondsLabel.text = seconds.toSecondStr()
        } else {
            timeLabel.text = Int(time).toSecondStr()
        }
    }

    //时间戳转成字符串
    private func formatTime(timeInterval: TimeInterval) -> String {
        let date:Date = Date(timeIntervalSince1970: timeInterval)
        return dateFormater.string(from: date as Date)
    }
    
    private var dateFormater: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss"
        return formatter
    }()
}

extension TimingViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return records.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
        var config = UIListContentConfiguration.cell()
        let record = records[indexPath.row]
        config.text = record.getResultStr()
        cell.contentConfiguration = config
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}
